<?php
/* 
 * Author: Quan Van Sinh
 * Email: sinhvnb@vietnambiz.com
 */
class photos{

   function photos(){}

    function get_string_url($arrRemoveParam=array('page')) {
        $strParamsGet = '';
        $i=0;
        in_array($key, $arrRemoveParam);
        foreach ($_GET as $key=>$item) {
            if($i==0 && !in_array($key, $arrRemoveParam)) {
                $strParamsGet .= $key.'='.$item;
            }else if($i!=0 && !in_array($key, $arrRemoveParam)) {
                $strParamsGet .= '&'.$key.'='.$item;
            }
            $i++;
        }
        return $strParamsGet;
    }
    function photosAction() {

        if(isset($_REQUEST['photosActionType'])) {
            $actionType = $_REQUEST['photosActionType'];
            switch ($actionType) {
                case 'addPhotos':
                    $this->addPhotos();
                    break;
                case 'deletePhoto':
                    $this->deletePhoto($_REQUEST['filename']);
                    break;
                default:
                    $this->getAllPhotos();
                }
            }
        }

        function deletePhoto($photo){
            global $config;
            $root = str_replace('/uploads', '', $config ['upload_dir']);
            $srcPhoto = $root.str_replace('thumb-137-113/', '', $photo);
            $photo137113 = $root.$photo;
            $photo4747 = $root.str_replace('thumb-137-113/', 'thumb-47-47/', $photo);
            unlink($srcPhoto);
            unlink($photo137113);
            unlink($photo4747);
            $loc = $config ['domain'].'/'.$config ['admin_section'].'/photos?'.  $this->get_string_url(array('photosActionType','filename','path'));
            header("Location: ".$loc);
        }

        function listDir($dir) {
            if(is_dir($dir)) {
                $arrIgnore = Array('.','..','Thumbs.db');
                if($handle = opendir($dir)) {
                    $arrDir = array();
                    while(($file = readdir($handle)) !== false) {
                        $pos = strpos($file, '.jp');
                        $pos1 = strpos($file, '.bm');
                        $pos2 = strpos($file, '.gi');
                        $pos3 = strpos($file, '.pn');
                        if(!in_array($file, $arrIgnore) && $pos==FALSE && $pos1==FALSE && $pos2==FALSE && $pos3==FALSE) {
                            $dirS = '<a href="?dir='.$dir.$file.'/&place='.$_GET['place'].'">'.$file.'</a>&nbsp;&nbsp;';
                            $arrDir[$dirS]=$file;
                        }
                    }

                    arsort($arrDir);
                    foreach ($arrDir as $k => $v) {
                        echo $k;
                    }

                }
                closedir($handle);
            }
        }
        function listImages($dir) {
            if(is_dir($dir)) {
                if($handle = opendir($dir)) {
                    $arrImage = array();
                    while(($file = readdir($handle)) !== false) {
                        $pos = strpos($file, '.jp');
                        if($pos!=FALSE) {
                            $outFile = $dir.$file;
                            $fileMTime = filemtime($outFile);
                            $arrImage[$outFile]=$fileMTime;
                        }
                    }
                }
                closedir($handle);
            }
            arsort($arrImage);

            $rowPerPage = 20;
            $page = intval($_REQUEST['page']);
            if($page<=0){
                $page = 1;
            }
            $totalRows = count($arrImage);
            $totalPages = ceil($totalRows/$rowPerPage);
            $_SESSION['pagingPhotos']['page'] = $page;
            $_SESSION['pagingPhotos']['totalPages'] = $totalPages;
            $start = (($page*$rowPerPage)-$rowPerPage);
            $arrImage = array_slice($arrImage, $start, $rowPerPage);

            foreach ($arrImage as $k => $v) {
                echo '<img class="imagesContextAction" onclick="javascript: returnToParent(\'/'.$k.'\');"  src="/'.$k.'" alt="'.$k.'"/>'."\n";
            }

        }

        function listImagesDescription($dir,$thumbDir) {
            if(is_dir($dir)) {
                if($handle = opendir($dir)) {
                    while(($file = readdir($handle)) !== false) {
                        $pos = strpos($file, '.jp');
                        if($pos!=FALSE) {
                            if (file_exists($thumbDir.$file)) {
                                $fileMTime = filemtime($dir.$file);
                                $arrImage[$file]=$fileMTime;
                            }
                        }
                    }
                }
                closedir($handle);
            }
            arsort($arrImage);

            $rowPerPage = 20;
            $page = intval($_REQUEST['page']);
            if($page<=0){
                $page = 1;
            }
            $totalRows = count($arrImage);
            $totalPages = ceil($totalRows/$rowPerPage);
            $_SESSION['pagingPhotos']['page'] = $page;
            $_SESSION['pagingPhotos']['totalPages'] = $totalPages;
            $start = (($page*$rowPerPage)-$rowPerPage);
            $arrImage = array_slice($arrImage, $start, $rowPerPage);

            foreach ($arrImage as $k => $v) {
                echo '<img class="imagesContextAction" onclick="javascript: returnToParent(\'/'.$dir.$k.'\');"  src="/'.$thumbDir.$k.'" alt="'.$k.'"/>'."\n";
            }
        }

        function addPhotos() {
            global $config;

            $photos = $_FILES['photos'];
            
            $thumbSize = Array('137-113','357-266',' 220-166');
            
            $upload_dir = $config ['upload_dir'].'/articles/'.date("Y").'/'.date("m");

            $now = time();

            for($i=0;$i<count($photos['name']);$i++) {
                if ((($photos["type"][$i] == 'image/gif') || ($photos["type"][$i] == 'image/jpeg')
                        || ($photos["type"][$i] == 'image/png') || ($photos["type"][$i] == 'image/jpg')) && ($photos["size"][$i] < 5000000)) {
                    $arrPhotoNameExplode = explode('.', $photos["name"][$i]);
                    $photoExtention = $arrPhotoNameExplode[(count($arrPhotoNameExplode)-1)];
                    $filename = $now.'-'.rand(0,999999).'.'.strtolower($photoExtention);
                    if (!file_exists($upload_dir)) {
                        if(!mkdir($upload_dir, 0777,true)) {
                            $_SESSION['rsMessages'] .= "<span class='error'>Can not create directory, please check permission.</span><br/>";
                        }
                    }
                    if (move_uploaded_file($photos["tmp_name"][$i],$upload_dir."/".$filename)) {
                        for($s=0;$s<count($thumbSize);$s++) {// start create thumbnail
                            $upload_dir_thumb = $upload_dir.'/thumb-'.$thumbSize[$s];
                            if (!file_exists($upload_dir_thumb)) {
                                if(!mkdir($upload_dir_thumb, 0777,true)) {
                                    $_SESSION['rsMessages'] .= "<span class='error'>Can not create thumb directory, please check permission.</span><br/>";
                                }
                            }
                            $wh = explode('-',$thumbSize[$s]);
                            $thumbnail_width = $wh[0];
                            $thumbnail_heigh = $wh[1];

                            //$output_thumb_filename = $upload_dir_thumb.'/'.basename($filename);
                            include_once (BASE_PATH."/ext/phpThumb/ThumbLib.inc.php");
                            $options = array('resizeUp' => true, 'jpegQuality'=>88);
                            //$fileData = file_get_contents($upload_dir."/".$filename);
                            //$thumb = PhpThumbFactory::create($fileData, $options, true);
                            $thumb = PhpThumbFactory::create($upload_dir."/".$filename, $options);
                            $thumb->adaptiveResize($thumbnail_width+10, $thumbnail_heigh+10);
                            $thumb->cropFromCenter($thumbnail_width, $thumbnail_heigh);
                            $thumb->save($upload_dir_thumb.'/'.$filename,'jpg');
                        }
                        $_SESSION['rsMessages'] .= "<span class='success'>".$photos["name"][$i]." upload successful!.</span><br/>";
                    }else {
                        $_SESSION['rsMessages'] .= "<span class='error'>Error, Can not upload photo: ".$photos["name"][$i].'</span><br/>';
                    }
                }else {
                    $_SESSION['rsMessages'] .= "<span class='error'>Invalid file ".$photos['name'][$i].'</span><br/>';
                }
            }
            $_SESSION['rsMessages'] .= "<span class='success'>Add new photos completed!</span><br/>";
        }
}

    ?>
